<template>
  <div class="app-container">
    
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label="单位名称">
          <el-input v-model="listQuery.item.company" placeholder="请输入单位名称"></el-input>
        </el-form-item>
        <el-form-item label="测点MAC">
          <el-input v-model="listQuery.item.deviceMac" placeholder="请输入测点MAC"></el-input>
        </el-form-item>
        <el-form-item label="所在区域">
          <el-cascader
            placeholder="请选择所在区域"
            v-model="listQuery.item.addressPArr"
            :options="areaList.children"
            :props="{
              label: 'label',
              value: 'label'
            }"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="listQuery.item.state" placeholder="请选择状态" clearable="">
            <el-option
              v-for="item in stateList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期范围">
          <el-date-picker
            v-model="listQuery.item.addTimeArr"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-search" @click="handleFilter" :loading="btnLoading">查询</el-button>
          <!-- <el-button 
            @click="handleCreate()" 
            :loading="btnLoading"
            type="success" 
            plain
            icon="el-icon-plus">
            新建测点
          </el-button> -->
          <el-button 
            @click="handleExport()" 
            :loading="btnLoading"
            type="success" 
            plain
            icon="el-icon-download">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="list"
      v-loading="listLoading"
      border 
      fit 
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="测点MAC" min-width="60">
        <template slot-scope="scope">
          <span>{{scope.row.deviceMac || '--'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="测点名称" min-width="60">
        <template slot-scope="scope">
          <span>{{scope.row.deviceName || '--'}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="电场数量" min-width="160">
        <template slot-scope="scope">
          <span>{{scope.row.adminstrative || '--'}}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="所属客户"  width="400">
        <template slot-scope="scope">
          <span>{{scope.row.company || '--'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在区域" width="160" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.addressP || '--'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="测点状态" width="80" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.state === 0">
            <span>在线</span>
          </template>
          <template v-if="scope.row.state === 1">
            <span>离线</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="接入日期" width="160">
        <template slot-scope="scope">
          <span>{{scope.row.modifyTime || '--'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" width="160">
        <template slot-scope="scope">
          <span>{{scope.row.addTime || '--'}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column fixed="right" align="center" label="操作" width="120"  class-name="small-padding fixed-width handle-td">
        <template slot-scope="scope">
          <i 
            class="el-icon-edit-outline" 
            title="编辑"
            @click="handleUpdate(scope.row)" 
          >
          </i>
          <el-popconfirm
            title="确定删除吗？"
            @onConfirm="handleDelete(scope.row, scope.$index)" 
          >
            <i 
              slot="reference"
              class="el-icon-delete" 
              title="删除"
            >
            </i>
          </el-popconfirm>
        </template>
      </el-table-column> -->
    </el-table>

    <div class="pagination-container">
      <el-pagination 
        background 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange" 
        :current-page="listQuery.page.num" 
        :page-size="listQuery.page.size" 
        layout="total, prev, pager, next, jumper" 
        :total="listQuery.page.total"
      >
      </el-pagination>
    </div>

    <el-dialog 
      :title="textMap[dialogStatus]" 
      :visible.sync="dialogFormVisible" 
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form 
        :rules="rules" 
        ref="dataForm" 
        :model="temp" 
        label-width="100px" 
        style='width:100%;'
      >
        <el-form-item label="MN号" prop="username">
          <el-input v-model="temp.username" placeholder="请输入MN号"></el-input>
        </el-form-item>

        <el-form-item label="所在区域" prop="adminstrativeArr">
          <el-cascader
            placeholder="请选择所在区域"
            v-model="temp.adminstrativeArr"
            :options="areaList.children"
            :props="{
              label: 'label',
              value: 'label'
            }"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="temp.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>

        <el-form-item label="公司名称" prop="company">
          <el-input v-model="temp.company" placeholder="请输入公司名称"></el-input>
        </el-form-item>

        <!-- <el-form-item label="所在岗位" prop="job">
          <el-input v-model="temp.job" placeholder="请输入所在岗位"></el-input>
        </el-form-item> -->

        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="temp.telephone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-form-item label="信用代码" prop="creditCode">
          <el-input v-model="temp.creditCode" placeholder="请输入信用代码"></el-input>
        </el-form-item>

        <el-form-item label="排污许可" prop="dischargePermit">
          <el-input v-model="temp.dischargePermit" placeholder="请输入排污许可"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogStatus=='create'" type="success" @click="createData" :loading="btnLoading">确定</el-button>
        <el-button v-else type="success" @click="updateData" :loading="btnLoading">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { addSave, updateSave, getList, deleteSave, exportExcel } from '@/api/device'
import { mapGetters } from 'vuex'

import areaList from '../../../static/json/area.json'

export default {
  name: 'IspIndex',
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  components: {
  },
  data() {
    return {
      btnLoading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑测点',
        create: '新建测点'
      },
      dialogVisible: false,
      temp: {
        username: '', // MN号
        adminstrativeArr: [],
        adminstrative: '', // 所在区域
        address: '', // 详细地址
        company: '', // 公司名称
        job: '', // 所在岗位
        telephone: '', // 联系电话
        creditCode: '', // 信用代码
        dischargePermit: '', // 排污许可
        userId: '' // 当前登录人ID
      },
      rules: {
        username: [
          { required: true, message: '请输入MN号', trigger: 'change' },
          { max: 50, message: 'MN号最大长度50位', trigger: 'change' }
        ],
        adminstrativeArr: [
          { required: true, message: '请选择所在区域', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'change' },
          { max: 255, message: '详细地址最大长度255位', trigger: 'change' }
        ]
      },
      listLoading: false,
      list: [],
      listQuery: {
        page: {
          num: 1,
          total: 0,
          size: 10
        },
        item: {
          userId: null,
          company: '', // 单位名称
          deviceMac: '', // 设备MAC
          addressP: '', // 所在区域
          addressPArr: [],
          state: '', // 状态
          startAddTime: '',
          endAddTime: '',
          addTimeArr: []
        }
      },
      // 所在区域数据
      areaList,
      stateList: [
        {
          value: 0,
          label: '在线'
        },
        {
          value: 1,
          label: '离线'
        }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  watch: {
    // 表单内容体
    temp: {
      handler: function(val, oldVal) {
      },
      deep: true
    },
    // 搜索条件体
    listQuery: {
      handler: function(val, oldVal) {
      },
      deep: true
    }
  },
  created() {
    this.listQuery.item.userId = this.token
    this.temp.userId = this.token * 1
    // 取列表
    this.getList()
  },
  activated() {
    // 取列表
    this.getList()
  },
  deactivated() {
  },
  methods: {
    // 导出
    handleExport() {
      const href = exportExcel(this.listQuery)
      console.log(href)
      window.location.href = href
    },
    // 改变每页显示条数
    handleSizeChange(val) {
      this.listQuery.page.size = val
      this.getList()
    },
    // 改变当前页面
    handleCurrentChange(val) {
      this.listQuery.page.num = val
      this.getList()
    },
    // 搜索
    handleFilter() {
      this.btnLoading = true
      this.listQuery.page.num = 1
      this.getList().then(() => {
        this.btnLoading = false
      }).catch(() => {
        this.btnLoading = false
      })
    },
    // 获取列表
    getList() {
      this.listLoading = true
      return getList(this.listQuery).then(response => {
        this.list = response.data
        // this.listQuery.page.total = response.totalpages * this.listQuery.page.size
        this.listQuery.page.total = response.totalData
        this.listLoading = false
      }).catch(err => {
        err
        this.listLoading = false
      })
    },
    // 重置数据
    resetTemp() {
      this.temp = {
        username: '', // MN号
        adminstrativeArr: [],
        adminstrative: '', // 所在区域
        address: '', // 详细地址
        company: '', // 公司名称
        job: '', // 所在岗位
        telephone: '', // 联系电话
        creditCode: '', // 信用代码
        dischargePermit: '', // 排污许可
        userId: this.token * 1 // 当前登录人ID
      }
      return this.temp
    },
    // 新建
    handleCreate(row) {
      this.productImgFilePathList = []
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, this.resetTemp(), row) // copy obj
      // 所在地区
      if (typeof this.temp.adminstrative !== 'undefined' && this.temp.adminstrative !== '') {
        this.temp.adminstrativeArr = this.temp.adminstrative.split('/')
      } else {
        this.temp.adminstrativeArr = []
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新建 - 保存
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 所在地区
          if (this.temp.adminstrativeArr.length !== 0) {
            this.temp.adminstrative = this.temp.adminstrativeArr.join('/')
          } else {
            this.temp.adminstrative = ''
          }
          this.btnLoading = true
          addSave(this.temp).then(response => {
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(err => {
            this.btnLoading = false
            err
          })
        }
      })
    },
    // 编辑 - 保存
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 所在地区
          if (this.temp.adminstrativeArr.length !== 0) {
            this.temp.adminstrative = this.temp.adminstrativeArr.join('/')
          } else {
            this.temp.adminstrative = ''
          }
          this.btnLoading = true
          updateSave(this.temp).then(response => {
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(err => {
            this.btnLoading = false
            err
          })
        }
      })
    },
    // 删除
    handleDelete(row) {
      deleteSave({
        id: row.id
      }).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }).catch(err => {
        err
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
